package com.lepu.app.fun.my.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.CircularImageView;
import com.eyzhs.app.R;
import com.lepu.app.fun.my.PubContentDetailActivity;
import com.lepu.app.fun.my.ReportActivity;
import com.lepu.app.fun.my.bean.BeanPubContentComment;
import com.lepu.app.main.activity.MainTabActivity;

public class AdapterPubContentComment extends BaseAdapter implements AsyncRequest{

	private String REQUEST_PRAISE = "request_praise";
	private static final int MSG_PRAISE_SUCESS = 11;
	private static final int MSG_PRAISE_FAIL = 12;
	private LayoutInflater mLayoutInflater = null;
	private Context mContext = null;
	private ArrayList<BeanPubContentComment> mArrayList = null;

	public TextView mPraiseText = null; //记录点赞数量
	private BeanPubContentComment mBean = null; //评论
	private int mHotCount;
	
	public AdapterPubContentComment(Context context,
			ArrayList<BeanPubContentComment> arrayList, int hotCount) {
		mContext = context;
		mLayoutInflater = LayoutInflater.from(context);
		mArrayList = arrayList;
		mHotCount = hotCount;
	}

	@Override
	public int getCount() {
		int size = 0;
		if (mArrayList != null && mArrayList.size() > 0) {
			size = mArrayList.size();
		}
		return size;
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		final ViewHolder holder;

		if (convertView == null) {
			convertView = mLayoutInflater.inflate(
					R.layout.my_pub_content_detail_comment_listitem, null);

			holder = new ViewHolder();

			LinearLayout itemLayout = (LinearLayout) convertView
					.findViewById(R.id.mainItemLayout);
			CircularImageView accountIconImageView = (CircularImageView) convertView
					.findViewById(R.id.iconImageView);
			TextView titleTextView = (TextView) convertView
					.findViewById(R.id.titleTextView);
			TextView storyTextView = (TextView) convertView
					.findViewById(R.id.storyTextView);
			TextView timeTextView = (TextView) convertView
					.findViewById(R.id.timeTextView);
			TextView bottomTitleTextView = (TextView) convertView
					.findViewById(R.id.bottomTitleTextView);
			LinearLayout replayLayout = (LinearLayout) convertView
					.findViewById(R.id.replayLayout);
			TextView replyNameTextView = (TextView) convertView
					.findViewById(R.id.replyNameTextView);
			TextView replyStoryTextView = (TextView) convertView
					.findViewById(R.id.replyStoryTextView);
			TextView replyContentTextView = (TextView) convertView
					.findViewById(R.id.replyContentTextView);
			TextView commentTitle = (TextView) convertView
					.findViewById(R.id.commentTitle);

			holder.itemLayout = itemLayout;
			holder.iconImageView = accountIconImageView;
			holder.titleTextView = titleTextView;
			holder.storyTextView = storyTextView;
			holder.timeTextView = timeTextView;
			holder.bottomTitleTextView = bottomTitleTextView;
			holder.replayLayout = replayLayout;
			holder.replyNameTextView = replyNameTextView;
			holder.replyStoryTextView = replyStoryTextView;
			holder.replyContentTextView = replyContentTextView;
			holder.commentTitle = commentTitle;

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		if(PubContentDetailActivity.getInstance() == null)
		{
			return convertView;
		}

		final BeanPubContentComment item = mArrayList.get(position);

		// holder.iconImageView.setImageBitmap(ImageUtilBase.getBitmapByResId(
		// mContext, R.drawable.default_icon_small));
		// if (!TextUtils.isEmpty(item.UserAvatar)) {
		// String fileName = EncodeMD5.getMd5(item.UserAvatar);
		// String filePath = SdLocal.getCacheImagePath(mContext,
		// fileName);
		// String imageUrl = Setting.getImageUrl(item.UserAvatar);
		//
		// BitmapManager.getInstance().loadBitmap(imageUrl, filePath,
		// holder.iconImageView, true); 1109525505906978967
		// }
		
		//title
		if(position == 0){
			holder.commentTitle.setVisibility(View.VISIBLE);
			if(mHotCount ==0){
				holder.commentTitle.setText("最新评论");
			}else{
				holder.commentTitle.setText("最热评论");
			}
			
		}else if(position == mHotCount){
			holder.commentTitle.setVisibility(View.VISIBLE);
			holder.commentTitle.setText("最新评论");
		}else{
			holder.commentTitle.setVisibility(View.GONE);
		}
		
		String imageUrl = Setting.getImageUrl(item.UserAvatar);
//		UniversalImageLoadTool.disPlay(imageUrl, holder.iconImageView,
//				R.drawable.app_ic_default_avatar_64);
		LoginUtil.loadSelfUserImage(mContext, holder.iconImageView, imageUrl);

		holder.titleTextView.setText(item.UserNickName);
		holder.storyTextView.setText(item.FavourCount + "  ");
		holder.storyTextView.setOnClickListener(new MoreOnclickListener(item, holder.storyTextView));
		
		if(!TextUtils.isEmpty(item.HasFavour) && item.HasFavour.equals("1")){
			holder.storyTextView.setSelected(true);
		}else{
			holder.storyTextView.setSelected(false);
		}

		holder.timeTextView.setText(DateUtilBase
				.friendly_time(item.RecordCreateTime));
		holder.bottomTitleTextView.setText(item.ReplyContent);

		// 评论内容
		if (!TextUtils.isEmpty(item.IsForbidden) && item.IsForbidden.equals("1")) {
			// 禁言
			holder.bottomTitleTextView.setTextColor(mContext.getResources()
					.getColor(R.color.color_mother_content_forbid));
		} else {
			// 非禁言
			holder.bottomTitleTextView.setTextColor(mContext.getResources()
					.getColor(R.color.color_text_black));
		}

		if (item.QuoteReply != null) {
			if (item.QuoteReply.UserNickName != null
					|| item.QuoteReply.Storey != null
					|| item.QuoteReply.ReplyContent != null) {
				holder.replayLayout.setVisibility(View.VISIBLE);
				holder.replyNameTextView.setText(item.QuoteReply.UserNickName);
				holder.replyContentTextView
						.setText(item.QuoteReply.ReplyContent);
				if ((PubContentDetailActivity.getInstance().mCurrentTag == 1)
						&& item.QuoteReply.Storey != null) {
					holder.replyStoryTextView.setText(item.QuoteReply.Storey
							+ "楼");
				} else {
					holder.replyStoryTextView.setText("");
				}

				// 回复h内容
				if (!TextUtils.isEmpty(item.QuoteReply.IsForbidden)
						&& item.QuoteReply.IsForbidden.equals("1")) {
					// 禁言
					holder.replyContentTextView.setTextColor(mContext
							.getResources().getColor(
									R.color.color_mother_content_forbid));
				} else {
					// 非禁言
					holder.replyContentTextView.setTextColor(mContext
							.getResources().getColor(R.color.color_text_black));
				}
			} else {
				holder.replayLayout.setVisibility(View.GONE);
			}
		} else {
			holder.replayLayout.setVisibility(View.GONE);
		}

		holder.itemLayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				showPopSend(item, position);
				
			}
		});
		
		holder.iconImageView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				LoginUtil.jumpUserInfo((BaseFragmentActivity)mContext, item.UserID);
			}
		});

		return convertView;
	}

	@SuppressLint("InflateParams")
	public void showPopSend(BeanPubContentComment beanPub,int position) {
		UtilityBase.closeSoftInput((Activity) mContext);

		View view = LayoutInflater.from(mContext).inflate(R.layout.mother_detail_comment_view, null);
		TextView repotText = (TextView) view.findViewById(R.id.mother_detail_report);
		TextView commentText = (TextView) view.findViewById(R.id.mother_detail_comment);
		TextView cannelText = (TextView) view.findViewById(R.id.mother_detail_cannel);
		
		repotText.setOnClickListener(new MoreOnclickListener(beanPub,position));
		commentText.setOnClickListener(new MoreOnclickListener(beanPub,position));
		cannelText.setOnClickListener(new MoreOnclickListener(beanPub,position));
		
		PopUtil.getInstance().showPopWindow((Activity) mContext, null, view,Gravity.BOTTOM, null, true);
	}
	
	 class MoreOnclickListener implements View.OnClickListener{
		 public BeanPubContentComment beanPub;
		 public int position;
		 private TextView textView;
		 public MoreOnclickListener(BeanPubContentComment beanPub, int position){
			 this.beanPub = beanPub;
			 this.position = position;
		 }
		 public MoreOnclickListener(BeanPubContentComment beanPub, TextView textView){
			 this.beanPub = beanPub;
			 this.textView = textView;
		 }
		 
		 public void onClick(View v) {
			 switch (v.getId()) {
				
				case R.id.mother_detail_report: //举报
                    boolean flagLoginReport = MainTabActivity.jumpLogin((BaseFragmentActivity)mContext);
					
					if(flagLoginReport){
						return;
					}
					
					Intent intent = new Intent(mContext, ReportActivity.class);
					intent.putExtra("reportType", 2);  //1 代表论坛主贴  2代表论坛评论
		            intent.putExtra("reportID", beanPub.ReplyID);
		            intent.putExtra("reportName", beanPub.ReplyContent);
		            ((BaseFragmentActivity)mContext).startActivity(intent,true);
		            PopUtil.getInstance().dismissPopWindow();
					break;
				case R.id.mother_detail_comment:
                    boolean flagLoginComment = MainTabActivity.jumpLogin((BaseFragmentActivity)mContext);
					
					if(flagLoginComment){
						return;
					}

					if(PubContentDetailActivity.getInstance() != null)
					{
						if (PubContentDetailActivity.getInstance().mCurrentTag == 0) {
							PubContentDetailActivity.getInstance().showKeyboard(true,beanPub.ReplyID, position, beanPub.UserNickName);
						} else if (PubContentDetailActivity.getInstance().mCurrentTag == 1) {
							PubContentDetailActivity.getInstance().showKeyboard(true,beanPub.ReplyID, position, beanPub.UserNickName);
						} else if (PubContentDetailActivity.getInstance().mCurrentTag == 2) {

						}
					}

					PopUtil.getInstance().dismissPopWindow();
					break;
				case R.id.mother_detail_cannel: 
					PopUtil.getInstance().dismissPopWindow();
					break;
				case R.id.storyTextView:
					if(LoginUtil.jumpLogin((BaseFragmentActivity)mContext)){
						return;
					}
					mBean = beanPub;
					if(TextUtils.isEmpty(mBean.FavourCount)){
						mBean.FavourCount="0";
					}
					mPraiseText = textView;
					if(mPraiseText.isSelected()){
						requestPraise(beanPub,0);
					}else{
						requestPraise(beanPub,1);
					}
					break;
				default:
					break;
		     }
		 }
	 }
	 
		//点赞/取消赞
		public void requestPraise(BeanPubContentComment bean, int praise) {
			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();
			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);
				
				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());
				params.put("OperationType", praise);//1点赞,0代表取消点赞
				params.put("TRID", bean.ReplyID);

			} catch (Exception e) {
			}
			map.put("ht", params);

			ApiClient.http_post(Setting.getBbsFavorUrl(), map, null, this,REQUEST_PRAISE, true, false);
		}
	
	private static class ViewHolder {
		LinearLayout itemLayout;
		CircularImageView iconImageView;
		TextView titleTextView;
		TextView timeTextView;
		TextView bottomTitleTextView;
		TextView storyTextView;
		LinearLayout replayLayout;

		TextView replyNameTextView;
		TextView replyStoryTextView;
		TextView replyContentTextView;
		TextView commentTitle;

	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_PRAISE_SUCESS:
				//更新点赞按钮
				if(mPraiseText.isSelected()){
					mPraiseText.setSelected(false);
					mBean.HasFavour = "0";
					mBean.FavourCount = String.valueOf(Integer.valueOf(mBean.FavourCount)-1);
					if(Integer.valueOf(mBean.FavourCount)<0){
						mBean.FavourCount = "0";
					}
					mPraiseText.setText(mBean.FavourCount);
					UIHelper.showToast(mContext, "取消点赞");
				}else{
					mPraiseText.setSelected(true);
					mBean.HasFavour = "1";
					mBean.FavourCount = String.valueOf(Integer.valueOf(mBean.FavourCount)+1);
					mPraiseText.setText(mBean.FavourCount);
					UIHelper.showToast(mContext, "点赞成功");
				}
				break;

			case MSG_PRAISE_FAIL:
				
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if(object.equals(REQUEST_PRAISE)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_PRAISE_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}

	}

	@Override
	public void RequestError(Object object, int arg1, String arg2) {
		if(object.equals(REQUEST_PRAISE)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_PRAISE_FAIL;
			mHandler.sendMessage(msg);
		}
	}
}
